using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.HospitalBed;

namespace SmartHealthcare.Write.Api.Application.Handler.HospitalBed
{
    public class CreateHospitalBedHandler : IRequestHandler<CreateHospitalBedCommand, APIResult<int>>
    {
        private readonly IBaseRepository<HospitalRoomModel> hospitalRoomRepository;
        private readonly IBaseRepository<HospitalBedModel> hospitalBedRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateHospitalBedHandler> logger;

        public CreateHospitalBedHandler(
            IBaseRepository<HospitalRoomModel> hospitalRoomRepository,
            IBaseRepository<HospitalBedModel> hospitalBedRepository,
            IMapper mapper,
            ILogger<CreateHospitalBedHandler> logger)
        {
            this.hospitalRoomRepository = hospitalRoomRepository;
            this.hospitalBedRepository = hospitalBedRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 创建病房并批量添加病床
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateHospitalBedCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            
            try
            {
                logger.LogInformation($"开始创建病房，病房编码:{request.HospitalRoomCode}，科室ID:{request.Department_id}，病房类型:{request.WardType}，病床数量:{request.Bed_total}");
                
                // 1. 创建病房
                var hospitalRoom = new HospitalRoomModel
                {
                    HospitalRoomCode = request.HospitalRoomCode,
                    Department_id = request.Department_id,
                    WardType = request.WardType,
                    Bed_total = request.Bed_total,
                    Bed_occupied = 0, // 默认病床使用数为0
                    Price = request.Price
                };

                logger.LogInformation($"准备创建病房实体，HospitalRoomCode:{hospitalRoom.HospitalRoomCode}");
                
                var roomResult = hospitalRoomRepository.Create(hospitalRoom);
                
                logger.LogInformation($"病房创建结果:{roomResult}，病房ID:{hospitalRoom.Id}");
                
                if (roomResult <= 0)
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "病房创建失败";
                    logger.LogError("病房创建失败，SaveChanges返回0");
                    return Task.FromResult(res);
                }

                // 获取刚创建的病房ID
                var roomId = hospitalRoom.Id;
                logger.LogInformation($"成功创建病房，病房ID:{roomId}");

                // 2. 批量创建病床
                var bedList = new List<HospitalBedModel>();
                for (int i = 1; i <= request.Bed_total; i++)
                {
                    var bed = new HospitalBedModel
                    {
                        HospitalRoomId = roomId, // 使用刚创建的病房ID
                        HospitalBedId = i, // 病床号自增
                        HospitalBedStatus = 0, // 0表示空状态
                        CurrentMedicalCard = string.Empty // 当前住院病人卡号为空
                    };
                    bedList.Add(bed);
                }

                logger.LogInformation($"准备创建{bedList.Count}张病床");

                // 批量添加病床
                int bedCount = 0;
                foreach (var bed in bedList)
                {
                    var bedResult = hospitalBedRepository.Create(bed);
                    logger.LogInformation($"创建病床结果:{bedResult}，病床ID:{bed.Id}");
                    if (bedResult > 0)
                    {
                        bedCount++;
                    }
                }

                logger.LogInformation($"病床创建完成，成功创建{bedCount}张，预期{request.Bed_total}张");

                if (bedCount == request.Bed_total)
                {
                    res.Code = APIEnums.Success;
                    res.Msg = $"病房创建成功，共添加{bedCount}张病床";
                    res.Data = (int)roomId;
                    logger.LogInformation($"病房创建成功，病房ID:{roomId}，病床数量:{bedCount}");
                }
                else
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = $"病房创建成功，但病床添加不完整，预期{request.Bed_total}张，实际添加{bedCount}张";
                    res.Data = (int)roomId;
                    logger.LogWarning($"病房创建成功，但病床添加不完整，病房ID:{roomId}，预期{request.Bed_total}张，实际添加{bedCount}张");
                }

                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "创建病房和病床时发生异常";
                logger.LogError(ex, "创建病房和病床时发生异常: {Message}", ex.Message);
                return Task.FromResult(res);
            }
        }
    }
} 